<?php
/**
 * 用户中心管理controller
 */
namespace App\Http\Controllers;
use App\Http\Models\Address;
use App\Http\Models\Bill;
use App\Http\Models\Coupon;
use App\Http\Models\Invoice;
use App\Http\Models\Log;
use App\Http\Models\Order;
use App\Http\Models\Outrent;
use App\Http\Models\Quota;
use App\Http\Models\User;
use App\Http\Util\UploadFile;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Session;

class UserController extends Controller
{
    public $user = null;//用户信息
    public $order = null;//订单相关
    public $addr = null;//地址关联
    public $quota = null;//额度管理
    public $bill = null;//账单资金相关
    public $color = null;//公用颜色配置
    public $outrent = null;//退租表操作
    public $coupon = null;//优惠券操作
    public function __construct()
    {
        $this->nav = '个人中心';
        $this->side = '个人信息';
        $this->order = new Order();
        $this->addr = new Address();
        $this->quota = new Quota();
        $this->bill = new Bill();
        $this->outrent = new Outrent();
        $this->color = CommonController::commmon_color_path();
        $this->coupon = new Coupon();
    }
    /**文件上传类型*/
    protected $FileType= array("jpg","png",'img','jpeg');
    /**订单状态*/
    protected $Orderstatus = array(
        '0'=>'未付款', '1'=>'已付款','2'=>'未发货','3'=>'代签收','4'=>'已签收','5'=>'退单','6'=>'完成'
    );
    /**账户信息列表*/
    public function account()
    {
        $this->side = '账户信息';
        $this->user = DB::table('frontusers')->find(session('user')->id);
        $param['cart'] = CommonController::shopcart(session('user')->id);
        $param['color'] = $this->color;//颜色
        $param['user_quota'] = DB::table('quota')->where('quota_user_id',session('user')->id)->first();//用户信用额度
        $param['user_account'] = DB::table('frontusers')->where('id',session('user')->id)->first();//用户余额
        $param['consume_page'] = Input::get('consume_page','1');
        $request_rent = [
            'status'=> '1',
            'userid' => trim(session('user')->id),
            'current_page' => $param['consume_page'],
            'offset'=>'0',
            'per_page'=> '5'
        ];
        $param['account_rent'] = $this->order->consume($request_rent);
        $param['bill_page'] = Input::get('bill_page','1');
        $request_bill = [
            'months_bill'=>date('Y-m',time()),
            'userid' => trim(session('user')->id),
            'current_page' => 1,
            'offset'=>'0',
            'per_page'=> '5'
        ];
        $param['account_bill'] = $this->bill->bill($request_bill);
        return view('usercenter.account',['user'=>$this->user,'param'=>$param,'nav'=>$this->nav,'side'=>$this->side]);
    }
    //账户信息消费记录
    public function account_consume()
    {
        $current_page = Input::get('consume_page','1');//获取页面当前页码
        $account_consume['userid'] = session('user')->id;
        $account_consume['per_page'] = '5';//页码长度
        $res = $this->order->consume($account_consume);//满足条件的所有数据[不带分页数据和带分页数据]
        $account_consume['page'] = ceil($res['res_count'][0]->num/$account_consume['per_page']);//当前查询的页码
        $page = Input::get('page');//查询页码操作
        $account_consume['file_path'] = env('STATIC_FILE_ERP_PATH');
        $account_consume['color']= $this->color;
        $account_consume['page_action'] = ['first','prev','next','last'];
        if($page=='first') {
            if($current_page<2){
                $result = ['res'=>'ok','msg'=>'已经是首页数据了'];
            }else{
                $account_consume['consume_page'] = '1';
                $result = ['res'=>'ok','msg'=>'查询分页成功','data'=>$res['res_page'],'account_consume'=>$account_consume];
            }
            return json_encode($result);
        }else if($page=='prev'){
            if($current_page<2){
                $result = ['res'=>'ok','msg'=>'已经是首页了'];
            }else if($current_page>=2){
                $account_consume['offset'] = ($current_page-2)*$account_consume['per_page'];
                $account_consume['consume_page']=$current_page-1;
                $ress = $this->order->consume($account_consume);
                $result = ['res'=>'ok','msg'=>'查询分页成功','data'=>$ress['res_page'],'account_consume'=>$account_consume];
            }
            return json_encode($result);
        }else if($page=='next'){
            if($current_page<$account_consume['page']){
                $account_consume['offset'] = ($current_page)*$account_consume['per_page'];
                $account_consume['consume_page']=$current_page+1;//当前页
                $ress = $this->order->consume($account_consume);
                $result = ['res'=>'ok','msg'=>'查询分页成功','data'=>$ress['res_page'],'account_consume'=>$account_consume];
            }else{
                $result = ['res'=>'ok','msg'=>'已经是末页了'];
            }
            return json_encode($result);
        }else{
            if($current_page==$account_consume['page']){
                $result = ['res'=>'ok','msg'=>'已经是末页了'];
            }else{
                $account_consume['offset'] = ($account_consume['page']-1)*$account_consume['per_page'];
                $account_consume['consume_page'] = $account_consume['page'];
                $res = $this->order->consume($account_consume);
                $result = ['res'=>'ok','msg'=>'查询分页成功','data'=>$res['res_page'],'account_consume'=>$account_consume];
            }
            return json_encode($result);
        }
    }
    //账户当月要付账单记录
    public function account_bill()
    {
        $current_page = Input::get('bill_page','1');//获取页面当前页码
        $account_bill['userid'] = session('user')->id;
        $account_bill['per_page'] = '5';//页码长度
        $res = $this->bill->bill($account_bill);
        $account_bill['page'] = ceil($res['res_count'][0]->num/$account_bill['per_page']);//当前查询的页码
        $page = Input::get('page');//查询页码操作
        $account_bill['file_path'] = env('STATIC_FILE_ERP_PATH');
        $account_bill['color']= $this->color;
        $account_bill['page_action'] = ['first','prev','next','last'];
        if($page=='first') {
            if($current_page<2){
                $result = ['res'=>'ok','msg'=>'已经是首页数据了'];
            }else{
                $account_bill['bill_page'] = '1';
                $result = ['res'=>'ok','msg'=>'查询分页成功','data'=>$res['res_page'],'account_bill'=>$account_bill];
            }
            return json_encode($result);
        }else if($page=='prev'){
            if($current_page<2){
                $result = ['res'=>'ok','msg'=>'已经是首页了'];
            }else if($current_page>=2){
                $account_bill['offset'] = ($current_page-2)*$account_bill['per_page'];
                $account_bill['bill_page']=$current_page-1;
                $ress = $this->bill->bill($account_bill);
                $result = ['res'=>'ok','msg'=>'查询分页成功','data'=>$ress['res_page'],'account_bill'=>$account_bill];
            }
            return json_encode($result);
        }else if($page=='next'){
            if($current_page<$account_bill['page']){
                $account_bill['offset'] = ($current_page)*$account_bill['per_page'];
                $account_bill['bill_page']=$current_page+1;//当前页
                $ress = $this->bill->bill($account_bill);
                $result = ['res'=>'ok','msg'=>'查询分页成功','data'=>$ress['res_page'],'account_bill'=>$account_bill];
            }else{
                $result = ['res'=>'ok','msg'=>'已经是末页了'];
            }
            return json_encode($result);
        }else{
            if($current_page==$account_bill['page']){
                $result = ['res'=>'ok','msg'=>'已经是末页了'];
            }else{
                $account_bill['offset'] = ($account_bill['page']-1)*$account_bill['per_page'];
                $account_bill['bill_page'] = $account_bill['page'];
                $res = $this->bill->bill($account_bill);
                $result = ['res'=>'ok','msg'=>'查询分页成功','data'=>$res['res_page'],'account_bill'=>$account_bill];
            }
            return json_encode($result);
        }
    }
    /**我的订单*/
    public function order()
    {
        $this->side = '我的订单';
        $this->user = DB::table('frontusers')->find(session('user')->id);
        $param['cart'] = CommonController::shopcart(session('user')->id);
        $param['order_status'] = trim(Input::get('orderstatus',''));
        /**订单筛选*/
        $param['request'] =[
            'status' => $param['order_status'],
            'userid' => $this->user->id,
            'pagesize' => 6
        ];
        $param['orderlist']= $this->order->lists($param['request'])->groupBy('order_id');
        $param['listpage'] = $this->order->lists($param['request']);
        $param['orderstatus'] = $this->Orderstatus; //订单状态
        $param['color'] = $this->color;//颜色
        return view('usercenter.order',['user'=>$this->user,'param'=>$param,'nav'=>$this->nav,'side'=>$this->side]);
    }
    /**
     * 订单删除
     * @id 订单详情orderdtid
     */
    public function order_delete($orderdtid)
    {
        /**校验是否是当前用户未付款订单,去订单id*/
        $isexist = $this->order->orderexist(session('user')->id,$orderdtid);
        if(empty($isexist)){
            $result = ['res'=>'error','msg'=>'你不能取消自己外的订单!'];
        }else{
            $res = $this->order->destroy($isexist->id,$orderdtid);
            if($res=='ok'){
                $result = ['res'=>'ok','msg'=>'取消订单成功!'];
            }else{
                $result = ['res'=>'error','msg'=>'取消订单失败,请刷新后再试!','data'=>$res];
            }
        }
        echo json_encode($result);
    }
    /**删除大订单*/
    public function order_deletes($orderid)
    {
        $userid = session('user')->id;
        $res = $this->order->destroys($orderid,$userid);
        if($res=='ok'){
            $result = ['res'=>'ok','msg'=>'删除成功!','data'=>$res];
        }else{
            $result = ['res'=>'error','msg'=>'删除失败,请刷新后再试!','data'=>$res];
        }
        echo json_encode($result);
    }
    /**
     * 订单明细
     * @id 订单id
     */
    public function orderdt($id)
    {
        $this->side = '我的订单';
        $this->user = DB::table('frontusers')->find(session('user')->id);
        $param['cart'] = CommonController::shopcart(session('user')->id);
        $param['orderdt'] = $this->order->orderdt($id);
        $param['orderstatus'] = $this->Orderstatus;//订单状态
        return view('usercenter.orderdt',['user'=>$this->user,'param'=>$param,'nav'=>$this->nav,'side'=>$this->side]);
    }
    /**在租家具*/
    public function rentfitment()
    {
        $this->side = '在租家具';
        $this->user = DB::table('frontusers')->find(session('user')->id);
        $param['cart'] = CommonController::shopcart(session('user')->id);
        $name = ['1'=>'在租记录','2'=>'报修记录','3'=>'退租订单'];
        /**在租列表*/
        $request=[
            'userid' => trim(session('user')->id),
            'status' =>trim(Input::get('status')),
            'pagesize' => 10
        ];
        if(in_array($request['status'],array(1,2,3))){
            $param['rent_status'] = $name[$request['status']];
        }else{
            $param['rent_status'] = '全部记录';
        }
        $param['rentlist'] = $this->order->rentorder($request);
        $param['color']=$this->color;//颜色
        return view('usercenter.rentfitment',['user'=>$this->user,'param'=>$param,'nav'=>$this->nav,'side'=>$this->side]);
    }
    /**在租状态筛选*/
    public function rent_status($status)
    {
        if($status){
            $result = ['res'=>'ok','msg'=>'条件获取可以筛选','data'=>$status];
        }else{
            $result = ['res'=>'error','msg'=>'没有获取筛选条件'];
        }
        echo json_encode($result);
    }
    /**退租*/
    public function rentback($id)
    {
        $this->side = '在租家具';
        $this->user = DB::table('frontusers')->find(session('user')->id);
        $param['cart'] = CommonController::shopcart(session('user')->id);
        $request=null;
        /**退租详情*/
        $param['rentback_dt'] = $this->order->orderdetails($id,$request);
        /**退租账单详情【查询当前及来说未付款账单，本月后不查询】*/
        $param['rentback_bill'] = $this->bill->bill_orderdt($id);
        $param['color'] = $this->color;
        if(is_object($param['rentback_dt'])){
            if($param['rentback_dt']->details_rent_type==1){
                $param['title']='退租—随租随还';
                /**随租随还商品,退货流程,未满3个月退货扣除押金,满3个月从押金里面扣除当月未缴账单,其余返回账户余额*/
                return view('usercenter.rentback_round',['user'=>$this->user,'param'=>$param,'nav'=>$this->nav,'side'=>$this->side]);
            }else{
                $param['title']='退租—租满即送';
                /**[租满即送,退单时,还清该在租下的所有当前所欠租赁费，违约金支付当前退租数量的商品，支付当前选择数量的违约商品]*/
                /***[违约金扣除整个租赁周期的5%]*/
                /**【租满即送,转随租随还时,还清该在租下的所有当前所欠租赁费,支付转租数量产品的押金，计算新的押金体系】*/
                return view('usercenter.rentback',['user'=>$this->user,'param'=>$param,'nav'=>$this->nav,'side'=>$this->side]);
            }
        }else{
            return view('errors.404');
        }
    }
    /**
     * 退租逻辑处理【都执行记录退租表操作，修改在租表;【租满回退额度,随租回退额度;租满转租生成新订单,账单表】】
     * 【租满即送退租，转随租；随租退租】【随租随还没有转租直接退租】
     * 【记录退租表，判断租满还是随租】
     * @type【1=>随租，2=>租满】
     */
    public function dorentback()
    {
        $type = trim(Input::get('type'));/**租满还是随租退租处理*/
        $data=[
            'userid'=>session('user')->id,
            'order_id'=>trim(Input::get('order_id')),                                 /**订单id*/
            'adr_id'=>trim(Input::get('adr_id')),                                     /**订单关联地址id*/
            'details_orderNo'=>trim(Input::get('details_orderNo')),
            'order_details_id'=>trim(Input::get('order_details_id')),
            'fitment_details_id'=>trim(Input::get('fitment_details_id')),          /**退租商品详情id*/
            'fitment_details_number'=>trim(Input::get('fitment_details_number')), /**退租数量*/
            'rentback_fix'=>trim(Input::get('rentback_fix')),                        //商品租满即送租金
            'rentback_nimb'=>trim(Input::get('rentback_nimb')),                      //商品随租随还租金
            'rentback_bond'=>trim(Input::get('rentback_bond')),                      //商品所需信用额度
            'outrent_type'=>trim(Input::get('outrent_type')),                        /**退租去向1退租2转随租*/
            'outrent_rent_orderid'=>null,                                                  /**转租生产订单详情id*/
            'details_rent_type'=>trim(Input::get('details_rent_type')),             /**租赁类型1随租2租满即送*/
            'outrent_bill'=>trim(Input::get('outrent_bill')),                        /**欠还款金额*/
            'outrent_bond'=>trim(Input::get('outrent_bond')),                        /**支付额度或押金金额*/
            'outrent_amount'=>trim(Input::get('outrent_amount')),                    /**需支付总额*/
            'orders_discount' => null,                                                      /***预留参数，转租优惠*/
            'outrent_reason'=>null,
            'checktime'=>null,
            'status'=>1,                                                                      /**退租结算状态0待执行钱没结算1完成结算*/
            'isdel'=>1,
            'created_at'=>date('Y-m-d H:i:s',time()),
            'updated_at'=>date('Y-m-d H:i:s',time())
        ];
        if($data['outrent_type']==1){
            $res_msg='退租';
        }else{
            $res_msg='转租';
        }
        if($type==1){ //随租随还处理
            $outrent_bill = $this->bill->bill_orderdtsum(trim(Input::get('order_details_id')));
            $data['outrent_bill'] = $outrent_bill;
            $res = $this->outrent->insert_outrent($data);
            if($res=='ok'){
                $result =['res'=>'ok','msg'=>$res_msg.'作成功,稍后我们会将你剩余的押金返还到您的会员余额内!'];
            }else{
                $result =['res'=>'error','msg'=>$res_msg.'操作失败!','data'=>$res];
            }
        } else { //租满即送处理
            $res = $this->outrent->insert_outrent($data);
            if($res=='ok'){
                $result =['res'=>'ok','msg'=>$res_msg.'操作成功!'];
            }else{
                $result =['res'=>'error','msg'=>$res_msg.'操作失败!','data'=>$res];
            }
        }
        echo json_encode($result);
    }
    /**售后*/
    public function rentrepair($id)
    {
        $this->side = '在租家具';
        $this->user = DB::table('frontusers')->find(session('user')->id);
        $param['cart'] = CommonController::shopcart(session('user')->id);
        $param['rentrepair_dt'] = $this->order->orderdetails($id);
        return view('usercenter.rentrepair',['user'=>$this->user,'param'=>$param,'nav'=>$this->nav,'side'=>$this->side]);
    }
    /**售后数据保存*/
    public function rentrepair_post()
    {
        //上传售后图片信息
        $file_data = $_FILES['repair_file'];
        $param = [
            'reason'=>Input::get('reason','')
        ];
        dd($file_data);
    }
    /** 我的账单*/
    public function bill()
    {
        $this->side = '我的账单';
        $this->user = DB::table('frontusers')->find(session('user')->id);
        $param['cart'] = CommonController::shopcart(session('user')->id);
        $param['color'] = $this->color;
        $userid=session('user')->id;
        //获取页面年月时间数据，若没有显示当前年月数据
        $param['month_time']=trim(Input::get('month_time',date('Y-m',time())));
        //用户账单月份划分(初始数据)
        $months_request=[
            'userid' => $userid,
            'month_time' => $param['month_time'],//查询月份下数据
            'per_page' => 5
        ];
        $bill_months_data = $this->bill->bill_months($months_request);//用户所有账单月数据
        $param['bill_months'] = $bill_months_data['res_page'];
        $param['pageNow'] = $bill_months_data['pageNow'];//当前月份实际页码
        $param['pageNum'] = $bill_months_data['pageNum'];
        //用户按月账单数据
        $monthlist_request = [
            'userid'=>$userid,
            'months_bill'=>$param['month_time'],
            'per_page'=>5
        ];
        $param['bill_month_list']= $this->bill->bill_month_list($monthlist_request);//账单月份的详细数据
        //未付款账单
        $param['bill_status_wait'] = $this->bill->bill_months_status(session('user')->id,0,$param['month_time']);
        //已付款金额
        $param['bill_status_finish'] = $this->bill->bill_months_status(session('user')->id,1,$param['month_time']);

        return view('usercenter.bill',['user'=>$this->user,'param'=>$param,'nav'=>$this->nav,'side'=>$this->side]);
    }
    //月账单月份分页
    public function bill_months()
    {
        $page_act=trim(Input::get('page_act'));//上一页下一页动作
        $pageNow= trim(Input::get('pageNow'));//当前页面记录的分页数
        $pageNum = trim(Input::get('pageNum'));//获取总页数
        $param = [
            'page_act_prev' => 'prev',
            'page_act_next' => 'next',
            'userid'=>session('user')->id,
            'per_page'=>5
        ];
        if($page_act=='prev'){
            if($pageNow>1){
                $param['pageNow'] = $pageNow-1;
                $bill_user = $this->bill->bill_months($param);
                if(count($bill_user['res_page'])>0){
                    $result = ['res'=>'ok','msg'=>'查询分页成功','param'=>$param,'data'=>$bill_user['res_page'],'num'=>$bill_user['res_num']];
                }else{
                    $result = ['res'=>'error','msg'=>'查询分页失败!'];
                }
            }else{
                $result=['res'=>'ok','msg'=>'已经是首页了,没有更早的数据了!'];
            }
            return json_encode($result);
        }else{
            if($pageNow<$pageNum){
                $param['pageNow'] = $pageNow+1;
                $bill_user = $this->bill->bill_months($param);
                if(count($bill_user['res_page'])>0){
                    $result = ['res'=>'ok','msg'=>'查询分页成功','param'=>$param,'data'=>$bill_user['res_page'],'num'=>$bill_user['res_num']];
                }else{
                    $result = ['res'=>'error','msg'=>'查询分页失败!'];
                }
            }else{
                $result=['res'=>'ok','msg'=>'已经是末页了,没有更多的数据了!'];
            }
            return json_encode($result);
        }
    }
    /**我的优惠券*/
    public function coupon()
    {
        $this->side = '我的优惠券';
        $this->user = DB::table('frontusers')->find(session('user')->id);
        $param['cart'] = CommonController::shopcart(session('user')->id);
        $coupon_param=['userid'=>session('user')->id];
        $param['coupon_useable'] = $this->coupon->coupon_useable($coupon_param);
        $param['coupon_used'] = $this->coupon->coupon_used($coupon_param);
        $param['coupon_overuse'] = $this->coupon->coupon_overuse($coupon_param);

        return view('usercenter.coupon',['user'=>$this->user,'param'=>$param,'nav'=>$this->nav,'side'=>$this->side]);
    }
    /**生成订单号规则*/
    public static function orderNo()
    {
        return "CZ".date('YmdHis').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }
    /**账户充值*/
    public function recharge()
    {
            $this->side = '账户充值';
            $this->user = DB::table('frontusers')->find(session('user')->id);
            $param['cart'] = CommonController::shopcart(session('user')->id);
            return view('usercenter.recharge',['user'=>$this->user,'param'=>$param,'nav'=>$this->nav,'side'=>$this->side]);
    }
    /*账户充值方法*/
    public function rechargee(){
        switch (Input::all()['paytype']){
            case '1':
                include_once env('WXPAY_PUBLIC')."wxpay/lib/WxPay.Api.php";
                include_once env('WXPAY_PUBLIC')."wxpay/example/WxPay.NativePay.php";
                include_once env('WXPAY_PUBLIC').'wxpay/example/log.php';
                $orderNo = self::orderNo();
                $account = array();
                $account = [
                    "userid" => session('user')->id,
                    "out_orderid" => $orderNo,
                    "account_flow" =>1,
                    "type" => 2,
                    "amount" =>intval(Input::all()['recharge']),
                    "describe" => "账户充值通过微信平台",
                    "isdel" => 0,
                    'created_at' => date('Y-m-d H:i:s',time()),
                    'updated_at' => date('Y-m-d H:i:s',time())
                ];
                $result = DB::table('account')->insert($account);
                if ($result ==false){
                    return back();
                }
                $param['orders_amount'] = intval(Input::all()['recharge']);
                $param['orders_orderNo'] = $orderNo;
                $this->user = DB::table('frontusers')->find(session('user')->id);
                $param['cart'] = CommonController::shopcart(session('user')->id);
                $param['name'] = $this->user->name;
                return view('wxpay.WXpay',['user' => $this->user, 'param' => $param, 'nav' => $this->nav]);
                break;
            case '2':
                $orderNo = self::orderNo();
                $account = array();
                $account = [
                    "userid" => session('user')->id,
                    "out_orderid" => $orderNo,
                    "account_flow" =>1,
                    "type" => 2,
                    "amount" =>intval(Input::all()['recharge']),
                    "describe" => "账户充值通过支付宝平台",
                    "isdel" => 0,
                    'created_at' => date('Y-m-d H:i:s',time()),
                    'updated_at' => date('Y-m-d H:i:s',time())
                ];
                $resultt = DB::table('account')->insert($account);
                $result = array();
                $result['orders_amount'] = Input::all()['recharge'];
                $result['orders_orderNo'] = $orderNo;
                $result['id'] = session('user')->id;
                $result['orders_user_name'] = session('user')->name;
                return view('pay.pagepay.pagepay', compact('result'));
                break;
        }

}
    /**免押金额度申请*/
    public function quota_apply()
    {
        $this->side = '免押金额度';
        $this->user = DB::table('frontusers')->find(session('user')->id);
        $param['cart'] = CommonController::shopcart(session('user')->id);
        /**是否有申请记录*/
        $param['quota_apply_dt'] = DB::table('applyquota_message')->where('userid',session('user')->id)->first();

        $param['quota_data'] = DB::table('quota')->where('quota_user_id',session('user')->id)->first();

        return view('usercenter.quota_apply',['user'=>$this->user,'param'=>$param,'nav'=>$this->nav,'side'=>$this->side]);
    }
    /**
     * 额度申请数据【新增和修改】
     * @file, @path, @fileTyp
     */
    public function quota_post()
    {
        /**是否有申请额度数据*/
        $table = DB::table('applyquota_message')->where('userid',session('user')->id)->first();
        if(!$table){
            $data = [
                'userid' => session('user')->id,
                'company_name' => trim(Input::get('company_name',null)),//公司名
                'company_phone' => trim(Input::get('company_phone',null)),//公司联系
                'company_addr' => trim(Input::get('company_addr',null)),//公司地址
                'socialcredit' => trim(Input::get('socialcredit',null)),//组织社会信用码
                'username' => trim(Input::get('username',null)),//法人/股东姓名
                'userphone' => trim(Input::get('userphone',null)),//法人/股东联系
                'identificatiomn' => trim(Input::get('identificatiomn',null)),//联系人身份证
                'relationship' => trim(Input::get('relationship',null)),//相关联系人
                'relatedname' => trim(Input::get('relatedname',null)),//相关联系人姓名
                'relatedphone' => trim(Input::get('relatedphone',null)),//相关联系人联系
                'status' => '0',//审核状态
                'check_time' => null,//审核时间
                'created_at' => date('Y-m-d H:i:s',time()),//创建时间
                'updated_at' => date('Y-m-d H:i:s',time())//更新时间
            ];
            $filetype = array("image/jpg","image/png",'image/gif','image/jpeg');
            $dir = date('Ym');
            $path = './' . $_ENV['STATIC_FILE_LOCAL_PATH'] . '/quota_img/' . $dir.'/' ;
            if($_FILES['company_img']['size']>0){
                if(!in_array($_FILES['company_img']['type'],$filetype)){
                    return back()->withErrors('企业营业执照上传图片类型不符合要求!')->withInput();
                }
                $company_img = CommonController::upload($_FILES['company_img'],$path,$this->FileType);
                if(!$company_img){
                    return back()->withErrors('企业营业执照上传失败!')->withInput();
                }
                $data['company_img'] = $path.$company_img['filename'];
            }
            if($_FILES['ident_face']['size']>0){
                if(!in_array($_FILES['ident_face']['type'],$filetype)){
                    return back()->withErrors('身份证正面上传图片类型不符合要求!')->withInput();
                }
                $ident_face = CommonController::upload($_FILES['ident_face'],$path,$this->FileType);
                if(!$ident_face){
                    return back()->withErrors('身份证正面上传失败!')->withInput();
                }
                $data['ident_face'] = $path.$ident_face['filename'];
            }else{
                return back()->withErrors('请上传身份证正面照!')->withInput();
            }
            if($_FILES['ident_backface']['size']>0){
                if(!in_array($_FILES['ident_backface']['type'],$filetype)){
                    return back()->withErrors('身份证背面上传图片类型不符合要求!')->withInput();
                }
                $ident_backface = CommonController::upload($_FILES['ident_backface'],$path,$this->FileType);
                if(!$ident_backface){
                    return back()->withErrors('身份证背面上传失败!')->withInput();
                }
                $data['ident_backface'] = $path.$ident_backface['filename'];
            }else{
                return back()->withErrors('请上传身份证背面照!')->withInput();
            }
            $res =  $this->quota->quota_apply($data);
            $quota_data = [
                'quota_user_id'=>session('user')->id,
                'quota_company_name'=>$data['company_name'],
                'quota_amount'=>0,
                'quota_current'=>0,
                'quota_zhima'=>0,
                'created_at'=>date('Y-m-d H:i:s',time()),
                'updated_at'=>date('Y-m-d H:i:s',time())
            ];
            $quota = DB::table('quota')->insertGetId($quota_data);
            if($quota<1){
                $logdt = [
                    'userid'=>session('user')->id,
                    'action'=>'/quota_post',
                    'detail'=>'提交申请额度数据,记录额度生产额度表出错',
                    'status'=>0,
                    'created_at'=>date('Y-m-d H:i:s',time()),
                    'updated_at'=>date('Y-m-d H:i:s',time())
                ];
                Log::insertlog($logdt);
            }
            if($res){
                return back()->withErrors('信息录入成功,你可以查询芝麻授权信用额度!')->withInput();
            }else{
                return back()->withErrors('申请信息录入系统失败请重试!')->withInput();
            }

        }else{
            /**数据更新重新审核*/
            $data = [
                'userid' => session('user')->id,
                'company_name' => trim(Input::get('company_name',null)),//公司名
                'company_phone' => trim(Input::get('company_phone',null)),//公司联系
                'company_addr' => trim(Input::get('company_addr',null)),//公司地址
                'socialcredit' => trim(Input::get('socialcredit',null)),//组织社会信用码
                'username' => trim(Input::get('username',null)),//法人/股东姓名
                'userphone' => trim(Input::get('userphone',null)),//法人/股东联系
                'identificatiomn' => trim(Input::get('identificatiomn',null)),//联系人身份证
                'relationship' => trim(Input::get('relationship',null)),//相关联系人
                'relatedname' => trim(Input::get('relatedname',null)),//相关联系人姓名
                'relatedphone' => trim(Input::get('relatedphone',null)),//相关联系人联系
                'status' => '0',//审核状态
                'updated_at' => date('Y-m-d H:i:s',time())//更新时间
            ];
            if(!$table->company_img){
                $filetype = array("image/jpg","image/png",'image/gif');
                $dir = date('Ym');
                $path = './' . $_ENV['STATIC_FILE_LOCAL_PATH'] . '/quota_img/' . $dir.'/' ;
                if($_FILES['company_img']['size']>0){
                    if(!in_array($_FILES['company_img']['type'],$filetype)){
                        return back()->withErrors('企业营业执照上传图片类型不符合要求!')->withInput();
                    }
                    $company_img = CommonController::upload($_FILES['company_img'],$path,$this->FileType);
                    if(!$company_img){
                        return back()->withErrors('企业营业执照上传失败!')->withInput();
                    }
                    $data['company_img'] = $path.$company_img['filename'];
                }
            }
            /**额度表添加公司名*/
            if(!$table->company_name && $data['company_name']!=''){
                $edit_quota = DB::table('quota')->where('quota_user_id',session('user')->id)->updated(['quota_company_name'=>$data['company_name']]);
            }
            $res =  DB::table('applyquota_message')->where('id',$table->id)->update($data);
            if($res){
                return back()->withErrors('补充信息添加成功,稍后会做相关审核方便您的额度信息补充!')->withInput();
            }else{
                return back()->withErrors('申请信息补充失败,请稍后重试,已录入系统需要修改信息，请联系客服!')->withInput();
            }
        }
    }
    /**用户申请额度信息回调*/
    public function quota_reback()
    {
        $input = Input::all();
        /**@authorization_code */
        $result = $this->quota->getzhima_auth_code('authorization_code',$input['auth_code']);
        $app_auth_tokens=$result->alipay_system_oauth_token_response;
        if(!empty($app_auth_tokens))
        {
            $app_auth_token = $app_auth_tokens->access_token;
            /*** 查询用户芝麻信用分* @transaction_id商户请求唯一标识 */
            $transaction_id = CommonController::orderNo();
            /***信用评分授权日志*/
            $logdt = [
                'userid'=>session('user')->id,
                'action'=>'/quota_reback',
                'detail'=>'商询号'.$transaction_id.'授权码'.$app_auth_tokens->access_token.'支付宝id'.$app_auth_tokens->alipay_user_id.'过来userid'.$app_auth_tokens->user_id,
                'status'=>1,
                'created_at'=>date('Y-m-d H:i:s',time()),
                'updated_at'=>date('Y-m-d H:i:s',time())
            ];
            Log::insertlog($logdt);
            $res = $this->quota->ident($transaction_id,$app_auth_token);
            /***评分查询日志*/
            $quota_current = ($res->zm_score-600)*100;
            /**更新用户信用额度表*/
            $table = DB::table('quota')->where('quota_user_id',session('user')->id)->first();
            $update = [
                'quota_amount'=>($table->quota_amount+$quota_current),
                'quota_current'=>($table->quota_current+$quota_current),
                'quota_zhima'=>$res->zm_score,
                'updated_at'=>date('Y-m-d H:i:s',time())
            ];
            $update_table= DB::table('quota')->where('quota_id',$table->quota_id)->update($update);

            return redirect('/user/quota');
        }else{
            $logdt = [
                'userid'=>session('user')->id,
                'action'=>'/quota_reback',
                'detail'=>'授权查询获取token失败!',
                'status'=>0,
                'created_at'=>date('Y-m-d H:i:s',time()),
                'updated_at'=>date('Y-m-d H:i:s',time())
            ];
            Log::insertlog($logdt);

            return back()->withErrors('获取授权失败请重试或联系客服!')->withInput();
        }

    }
    /**
     * 免押金额度列表
     * 初始提交额度申请，可以申请芝麻信用，审核后可提交提升额度
     */
    public function quota()
    {
        $this->side = '信用额度';
        $this->user = DB::table('frontusers')->find(session('user')->id);
        $param['cart'] = CommonController::shopcart(session('user')->id);
        /**登陆用户额度申请信息表记录*/
        $param['quota_apply_dt'] = DB::table('applyquota_message')->where('userid',session('user')->id)->first();
        /***没有申请信用额度记录*/
        if(!$param['quota_apply_dt']){
            return redirect('/user/quota_apply');
        }else{
            /**执行申请芝麻信用*/
            $param['redirect'] = 'http://www.mzujie.com/quota_rebac';
            /**判断是否有额度数据*/
            $param['quota'] = DB::table('quota')->where('quota_user_id',session('user')->id)->first();
            /**额度使用详情*/
            if(!empty($param['quota'])){
                $param['quota_data_dt'] = $this->quota->quota_data_dt($param['quota']->quota_id);
            }
            /**提升额度申请*/
            $param['quota_add']=DB::table('quota_add')->where('userid',session('user')->id)->orderBy('updated_at','desc')->first();

            return view('usercenter.quota',['user'=>$this->user,'param'=>$param,'nav'=>$this->nav,'side'=>$this->side]);
        }
   }
    /**查看额度详情，未填的可修改*/
    public function quota_add()
    {
        $this->side = '免押金额度';
        $this->user = DB::table('frontusers')->find(session('user')->id);
        $param['cart'] = CommonController::shopcart(session('user')->id);

        return view('usercenter.quota_add',['user'=>$this->user,'param'=>$param,'nav'=>$this->nav,'side'=>$this->side]);
    }
    /**申请提升额度表单提交*/
    public function quota_add_post()
    {
        $quota_data = DB::table('quota')->where('quota_user_id',session('user')->id)->first();
        /**文件上传准备*/
        $filetype = array("image/jpg","image/png",'image/gif','image/jpeg');
        $dir = date('Ym');
        $path = './' . $_ENV['STATIC_FILE_LOCAL_PATH'] . '/quota_img/' . $dir.'/' ;
        if($_FILES["quota_apply"]['size']>0){
            if(!in_array($_FILES["quota_apply"]['type'],$filetype)){
                return back()->withErrors('上传文件类型不符合要求!')->withInput();
            }
        }else{
            return back()->withErrors('请上传文件!')->withInput();
        }
        DB::beginTransaction();
        try{
            $data = [
                'quotaid'=>$quota_data->quota_id,
                'userid'=>session('user')->id,
                'reason'=>Input::get('apply_reason'),
                'quota_img'=>null,
                'check_time'=>null,
                'status'=>0,
                'created_at'=>date('Y-m-d H:i:s',time()),
                'updated_at'=>date('Y-m-d H:i:s',time())
            ];
            $res = DB::table('quota_add')->insertGetId($data);
            if(!$res){
                DB::rollback();
                return back()->withErrors('数据添加失败!')->withInput();
            }
            $quota_img = CommonController::upload($_FILES['quota_apply'],$path,$this->FileType);
            if(!$quota_img){
                DB::rollback();
                return back()->withErrors('上传文件失败!')->withInput();
            }
            $edit_data = ['quota_img'=>$path.$quota_img['filename']];
            $edit = DB::table('quota_add')->where('id',$res)->update($edit_data);
            if(!$edit){
                unlink($path.$quota_img['filename']);
                return back()->withErrors('数据保存失败!')->withInput();
            }
            DB::commit();
            return redirect('/user/quota');
        }catch(Exception $e){
            DB::rollback();
            return back()->withErrors('额度提升文件提交失败,请重试!')->withInput();
        }
    }
    /**修改额度详情表显示状态，用户执行删除自己额度操作*/
    public function quota_editisdel($id)
    {
        $data = [
            'quota_detail_isdel'=>0,
            'updated_at'=>date('Y-m-d H:i:s',time())
        ];
        $res = DB::table('quota_detail')->where('quota_detail_id',$id)->update($data);
        if($res)
        {
            $result = ['res'=>'ok','msg'=>'删除成功'];
        }else{
            $result = ['res'=>'error','msg'=>'删除失败'];
        }
        echo json_encode($result);
    }
    /**芝麻信用额度查询*/
    public function getzhima()
    {
        $header ='https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?';
        $app_id ='&app_id=2017100909208205&scope=auth_zhima&redirect_uri=';
        $redirect = 'http://mzujie.com/quota_reback';
        $curl = $header.$app_id.UrlEncode($redirect);
        $html = file_get_contents($curl);
        $html = iconv("gb2312", "utf-8//IGNORE",$html);
        echo $html;
    }
    /**收货地址管理*/
    public function address()
    {
        $this->side = '收货地址';
        $this->user = DB::table('frontusers')->find(session('user')->id);
        $address = new Address();
        $param = array(
            'user_id'=>$this->user->id
        );
        $param['address'] = $address->lists($param['user_id']);
        $param['cart'] = CommonController::shopcart(session('user')->id);

        return view('usercenter.address',['user'=>$this->user,'param'=>$param,'nav'=>$this->nav,'side'=>$this->side]);
    }
    /**
     * 收货地址新增
     * @id 用户id
     */
    public function addaddr($id)
    {
        $input = Input::all();
        /**校验如果没有默认地址，添加默认为默认地址*/
        $codereview = DB::table('address')->where('addr_status',1)->get();
        if($codereview){
            $input['addr_status'] = 1;
        }
        $param = [
            'addr_user_id' => $id,
            'addr_rename' => trim($input['rename']),
            'addr_area' => trim($input['addr_area']),
            'addr_city' => trim($input['addr_city']),
            'addr_town' => trim($input['addr_town']),
            'addr_detail' => trim($input['addr_detail']),
            'addr_rephone' => trim($input['rephone']),
            'addr_status' => trim($input['addr_status']),
            'created_at' => date('Y-m-d H:i:s',time()),
            'updated_at' => date('Y-m-d H:i:s',time())
        ];

        if(empty($param['addr_rename'])){
            $res = ['res'=>'error','msg'=>'收货人不能为空!'];return json_encode($res);
        }
        if(empty($param['addr_area'])){
            $res = ['res'=>'error','msg'=>'地址省/直辖市必选!'];return json_encode($res);
        }
        if(empty($param['addr_city'])){
            $res = ['res'=>'error','msg'=>'地址市/直辖市郊县必选!'];return json_encode($res);
        }
        if(empty($param['addr_detail'])){
            $res = ['res'=>'error','msg'=>'收货具体地址必填!'];return json_encode($res);
        }
        if(empty($param['addr_rephone'])){
            $res = ['res'=>'error','msg'=>'收货人电话不能为空!'];return json_encode($res);
        }
        $pre_phone = '/^1[34578]\d{9}$/';
        if(!preg_match($pre_phone,$param['addr_rephone'])){
            $res = ['res'=>'error','msg'=>'请输入正确格式手机号!'];return json_encode($res);
        }
        /**创建地址入库*/
        $addr = new Address();
        $res = $addr->add($param);
        if($res != 'ok'){
            $res = ['res'=>'error','msg'=>'创建失败!请重试!','data'=>$res];return json_encode($res);
        }else{
            $res = ['res'=>'ok','msg'=>'创建地址成功!'];return json_encode($res);
        }
    }
    /**
     * 默认地址设置
     * @id 地址表主键
     */
    public function defaultad($id)
    {
        $addr = new Address();
        $res = $addr->defaultad($id);
        if($res=='ok'){
            $result = ['res'=>'ok','msg'=>'设置默认地址成功!'];return json_encode($result);
        }else{
            $result = $result = ['res'=>'error','msg'=>'设置失败请重试!','data'=>$res];return json_encode($result);
        }

    }
    /**
     * 收货地址删除
     * @id 地址表主键
     */
    public function addrdestroy($id)
    {
        $res = Address::where('addr_id',$id)->update(['addr_isdel'=>0]);
        if(!$res){
            $result = ['res'=>'error','msg'=>'地址删除失败!'];return json_encode($result);
        }else{
            $result = ['res'=>'ok','msg'=>'删除成功!'];return json_encode($result);
        }
    }
    /**发票列表*/
    public function invoice()
    {
        $this->side = '发票信息';
        $this->user = DB::table('frontusers')->find(session('user')->id);
        $param['request'] = array(
            'status'=>1,
            'isdel' => 1,
            'pagesize' => 15
        );
        $invoice = new Invoice();
        $param['invoice'] = $invoice->lists($param['request']);
        $param['cart'] = CommonController::shopcart(session('user')->id);
        /**收货地址查看*/
        $param['addr'] = $this->addr->lists(session('user')->id);
        $invoice_param=array(
            'userid'=>session('user')->id,
            'pagesize'=>10
        );
        $param['invoice_user'] = $invoice->invoice_used($invoice_param);

        return view('usercenter.invoice',['user'=>$this->user,'param'=>$param,'nav'=>$this->nav,'side'=>$this->side]);
    }
    /**发票申请*/
    public function invoiceapply()
    {
        $input = Input::all();
        $param = [
            'invoice_user_id' => session('user')->id,
            'invoice_amount' => trim($input['invoice_amount']),
            'invoice_content' => trim($input['invoice_content']),
            'invoice_type' => trim($input['invoice_type']),
            'invoice_company_tax' => trim($input['invoice_company_tax']),
            'invoice_company_name' => trim($input['invoice_company_name']),
            'invoice_status' => 1,
            'invoice_isdel' => 1,
            'invoice_address_id' => trim($input['addr_id']),
            'created_at'=>date('Y-m-d H:i:s',time()),
            'updated_at'=>date('Y-m-d H:i:s',time())
        ];
        if(!preg_match('/^[1-9]\d*$/',$param['invoice_amount']))
        {
            return back()->withErrors('请输入合法正整数作为开票金额!')->withInput();
        }
        //计算用户可发发票额度
        $invoice_count = DB::table('bill')
            ->where('userid',session('user')->id)
            ->where('status',1)
            ->sum('amount');
        //已开具发票总额
        $invoice_used = DB::table('invoice')
            ->where('invoice_user_id',session('user')->id)
            ->where('invoice_status','>',1)
            ->sum('invoice_amount');
        if($param['invoice_amount']>($invoice_count-$invoice_used)){
            return back()->withErrors('本次开票金额大于你消费累计可开发票额最大值!')->withInput();
        }
        $res = DB::table('invoice')->insertGetId($param);
        if($res>0){
            return redirect('/user/invoice');
        }else{
            return back()->withErrors('请稍后重试,申请发票失败!')->withInput();;
        }
    }
    /**
     * 修改已申请通过发票状态
     * @id发票表id
     */
    public function invoice_ensure($id)
    {
        $res = DB::table('invoice')
            ->where('invoice_id',$id)
            ->update(['invoice_status'=>3,'updated_at'=>date('Y-m-d H:i:s',time())]);
        if($res){
            $result=['res'=>'ok','msg'=>'确认发票收到成功!'];
        }else{
            $result=['res'=>'error','msg'=>'确认发票收到失败!'];
        }
        echo json_encode($result);
    }
    /**
     * 个人信息
     */
    public function user()
    {
        $this->user = DB::table('frontusers')->find(session('user')->id);
        $param['cart'] = CommonController::shopcart(session('user')->id);

        return view('usercenter.user',['user'=>$this->user,'param'=>$param,'nav'=>$this->nav,'side'=>$this->side]);
    }
    /**
     * 个人信息修改
     * @param Request $request
     * @param int $id
     * @return Response
     */
    public function update(Request $request,$id)
    {
        $type = trim(Input::get('type'));
        $user = User::find($id);
        /**昵称修改*/
        if($type=='name'){
            $name = trim(Input::get('name'));
            $user->name = $name;
            $res = $user->save();
            if($res){
                $user = User::find($id);
                Session::put('user',$user);
                $result = ['res'=>'ok','msg'=>'姓名修改成功'];return json_encode($result);
            }else{
                $result = ['res'=>'error','msg'=>'姓名修改失败'];return json_encode($result);
            }
        }/**邮箱修改*/
        else if($type=='email'){
            $email = trim(Input::get('email'));
            $email_match = "/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i";
            if(!preg_match($email_match,$email)){
                $result = ['res'=>'error','msg'=>'邮箱不符合规范'];return json_encode($result);
            }
            $ismail = DB::table('frontusers')->where('status',1)
                ->where(function ($query) use ($email){
                    $query->where('email',$email);
                })->first();

            if(!empty($ismail)){
                $result = ['res'=>'error','msg'=>'该邮箱已存在系统!'];return json_encode($result);
            }

            $user->email = $email;
            $res = $user->save();
            if($res){
                $result = ['res'=>'ok','msg'=>'邮箱修改成功'];return json_encode($result);
            }else{
                $result = ['res'=>'error','msg'=>'失败!'];return json_encode($result);
            }
        } /**密码修改*/
        else if($type=='password'){
            $oldpassword = trim(Input::get('oldpassword'));
            $password = trim(Input::get('password'));
            $repassword = trim(Input::get('repassword'));

            if(!Hash::check($oldpassword,$user->password)){
                $result = ['res'=>'error','msg'=>'原密码校验错误!'];return json_encode($result);
            }else if($password != $repassword){
                $result = ['res'=>'error','msg'=>'两次密码输入不一致!'];return json_encode($result);
            }else{
                if (strlen($password) < 6 || strlen($password) > 20) {
                    $result = ['res'=>'error','msg'=>'密码长度要在6-12位之间!'];return json_encode($result);
                }
                $user->password = Hash::make($password);
                $res = $user->save();
                if($res){
                    $result = ['res'=>'ok','msg'=>'密码修改成功'];return json_encode($result);
                }else{
                    $result = ['res'=>'error','msg'=>'密码修改失败!'];return json_encode($result);
                }
            }
        }

    }
    /**
     * 用户头像修改功能
     */
    public function avatar(Request $request,$id)
    {
        $isexsts = DB::table('frontusers')->where('id',$id)->select('avator','status')->first();
        $key = $_FILES['avatar'];
        $dir = date('Ym');
        $path = './' . $_ENV['STATIC_FILE_LOCAL_PATH'] . '/avatar/' . $dir.'/' ;
        if(!empty($isexsts->avator) && file_exists($isexsts->avator)){
            DB::beginTransaction();
            try{
                $res = unlink($isexsts->avator);
                if(!$res) {
                    DB::rollback();
                    return back()->withErrors('修改头像删除原头像失败!')->withInput();
                }
                $upload = $this->upload($key, $path);
                if(!$upload['upload']) {
                    DB::rollback();
                    return back()->withErrors('修改头像上传文件失败!')->withInput();
                }
                $user = User::find($id);
                $user->avator = $path.$upload['filename'];
                $user->updated_at = date('Y-m-d H:i:s',time());
                if(!$user->save()) {
                    DB::rollback();
                    return back()->withErrors('修改头像保存入库失败!')->withInput();
                }
                DB::commit();
                return redirect('/user');
            }catch(Exception $e){
                DB::rollback();
                return back()->withErrors('修改头像失败!')->withInput();
            }
        }else{
            $upload = $this->upload($key, $path);
            if(!$upload) {
                return back()->withErrors('文件上传失败!')->withInput();
            }
            $user = User::find($id);
            $user->avator = $path.$upload['filename'];
            $user->updated_at = date('Y-m-d H:i:s',time());
            if(!$user->save()) {
                unlink($upload['filename']);
                return back()->withErrors('保存入库失败!')->withInput();
            }
            return redirect('/user');
        }
    }
    /**
     * 文件上传
     * @param $key           上传字段名
     * @param $path          上传主路径('/'结尾)
     * @param $save_path     主路径下的文件夹('/'结尾)
     * @param $extent_path   扩展文件夹('/'结尾)
     * @param $type         文件类型限制
     */
    protected function  upload($key, $path, $save_path = '', $extent_path = '')
    {
        $upload = new UploadFile(); // 实例化上传类
        $upload->allowExts = $this->FileType; //设置附件上传类型
        $upload->maxSize = 1024 * 1000 * 1000 * 20; // 设置附件上传大小20M
        $upload->savePath = $path . $save_path . $extent_path; // 设置附件上传目录
        $upload->uploadReplace = true; //存在同名是否覆盖
        $upload->saveRule = str_pad(rand(000000,999999),'6','0',STR_PAD_LEFT ).date('YmdHis',time()); //文件重命名

        if ($upload->uploadOne($key)) {
            $rs = $upload->getUploadFileInfo();
            $result = array(
                'upload' => true,
                'filename'=> $upload->saveRule.'.'.substr($key['name'], strrpos($key['name'], '.')+1),
                'info' => $rs
            );
        } else {
            $result = array(
                'upload' => false,
                'info' => $upload->getErrorMsg()
            );
        }
        return $result;
    }

}
